# core/toc.py
from bs4 import BeautifulSoup  # 假设使用BeautifulSoup解析HTML


def generate_toc_html(html_content: str) -> str:
    """
    根据HTML内容中的标题结构生成目录HTML。

    Args:
        html_content: 包含标题和锚点的HTML字符串。

    Returns:
        生成的目录HTML字符串。
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    headings = soup.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])
    if not headings:
        return ''

    toc_list = []
    current_level = 0
    stack = []  # 用于跟踪当前嵌套层级

    for heading in headings:
        level = int(heading.name[1:])  # h1 -> 1, h2 -> 2
        text = heading.get_text(strip=True)
        anchor = heading.get('id', '')

        # 使用栈来管理嵌套层级，确保目录结构正确
        # 这个逻辑可能需要拆分成 _process_heading_level 等函数
        while stack and stack[-1]['level'] >= level:
            stack.pop()

        if stack:
            parent_item = stack[-1]
            new_item = {'level': level, 'text': text, 'anchor': anchor, 'children': []}
            parent_item['children'].append(new_item)
            stack.append(new_item)
        else:
            new_item = {'level': level, 'text': text, 'anchor': anchor, 'children': []}
            toc_list.append(new_item)
            stack.append(new_item)

    # 将解析后的结构转换为HTML字符串
    # 这个转换逻辑也可能需要拆分
    def build_toc_html(items, level=1):
        html = '<ul class="toc-level-' + str(level) + '">\n'
        for item in items:
            html += f'  <li><a href="#{item["anchor"]}">{item["text"]}</a>\n'
            if item['children']:
                html += build_toc_html(item['children'], level + 1)
            html += '  </li>\n'
        html += '</ul>\n'
        return html

    toc_html = '<div class="toc">\n' + build_toc_html(toc_list) + '</div>\n'
    return str(toc_html) if toc_list else ''
